package com.hexiang.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.RPCHook;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class SimpleBatchMessageMQProducer {

    private String topic = "test_simple_batch_topic";

    private String producerGroup = "simple_batch_producer_group";

    private String nameServer = "127.0.0.1:9876";

    private DefaultMQProducer defaultMQProducer;

    @PostConstruct
    public void start() throws MQClientException {
        defaultMQProducer = new DefaultMQProducer(producerGroup, getAclRPCHook());
        defaultMQProducer.setNamesrvAddr(nameServer);
        defaultMQProducer.start();
    }

    @PreDestroy
    public void shutdown() {
        defaultMQProducer.shutdown();
    }

    RPCHook getAclRPCHook() {
        return new AclClientRPCHook(new SessionCredentials("rocketmq_u1", "12345678"));
    }

    /**
     * 简单批量发送消息
     */
    public void sendBatchMsg() {
        List<Message> messages = new ArrayList<>();
        messages.add(new Message(topic, "TagA", "OrderID001", "Hello world 0".getBytes()));
        messages.add(new Message(topic, "TagA", "OrderID002", "Hello world 1".getBytes()));
        messages.add(new Message(topic, "TagA", "OrderID003", "Hello world 2".getBytes()));
        try {
            SendResult sendResult = defaultMQProducer.send(messages);
            log.warn("sendResult " + sendResult);
        } catch (Exception e) {
            log.error("sendBatchMsgErr", e);

        }
    }

}